package br.edu.catolica.sadbc.core.manager;

import java.io.Serializable;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.transaction.Transaction;

import br.edu.catolica.sadbc.core.exception.BusinessObjectException;
import br.edu.catolica.sadbc.core.util.Crypto;
import br.edu.catolica.sadbc.core.util.Soundex;
/**
 * 
 * @author robert.resende
 *
 */
@Scope(ScopeType.CONVERSATION)
public abstract class AbstractManager {

	private static final String SALT = "Ide@l1z3#2903";
	
	protected static final String RESULT_UPDATE = "RESULT_UPDATE";
	protected static final String RESULT_SEARCH = "RESULT_SEARCH";
	protected static final String RESULT_INSERT = "RESULT_INSERT";
	protected static final String RESULT_DETAIL = "RESULT_DETAIL";
	protected static final String RESULT_EXCLUDE = "RESULT_EXCLUDE";

	@Logger
	protected Log log;

	@In
	protected EntityManager entityManager;

	public void salvar(Serializable entity) throws BusinessObjectException {
		salvar(entity, true);
	}

	protected void salvar(Serializable entity, boolean flushed) throws BusinessObjectException {
		entityManager.persist(entity);
		if (flushed) {
			entityManager.flush();
		}
	}

	protected void salvar(Serializable entity, boolean updated, boolean flushed) throws BusinessObjectException {
		if (updated) {
			entityManager.merge(entity);
		} else {
			entityManager.persist(entity);
		}

		if (flushed) {
			entityManager.flush();
		}
	}

	public void excluir(Serializable entity) throws BusinessObjectException {
		salvar(entity, true);
	}

	protected void excluir(Serializable entity, boolean flushed) throws BusinessObjectException {
		entityManager.remove(entity);

		if (flushed) {
			entityManager.flush();
		}
	}
	
	protected void transactionBegin() throws IllegalStateException, SecurityException, SystemException, NotSupportedException {
		Transaction.instance().rollback();
		Transaction.instance().begin();
	}

	protected String encrypt(String password, String sal) {
		return Crypto.instance().encoding(password, sal + SALT);
	}

	protected String convertSound(String value) {
		return Soundex.convertSound(value);
	}

	@SuppressWarnings("rawtypes") 
	protected boolean isEmpty(Collection list) {
		return (list == null || list.isEmpty());
	}

	public Log getLog() {
		return log;
	}

}
